import SystemUtil from 'utils/systemUtil';

import moment from 'moment';

export default class Base {
  initObject(obj = {}, propertyList = [], hasNull = true, defaultValue = '', hasTrim = false) {
    for (let i = 0; i < propertyList.length; i++) {
      const property = propertyList[i];
      let value = obj[property];
      if (SystemUtil.isEmpty(value)) {
        if (!hasNull) {
          continue;
        }
        value = defaultValue;
      } else {
        if (hasTrim && typeof value === 'string') {
          value = value.trim();
        }
      }
      this[property] = value;
    }
  }

  getOnePic(pic) {
    if (SystemUtil.isEmpty(pic)) {
      return '';
    }
    let pics = pic.split(',');
    return pics[0];
  }

  checkRequired(propertyList = []) {
    for (let i = 0; i < propertyList.length; i++) {
      let property = propertyList[i];
      let value = this[property];
      if (SystemUtil.isEmpty(value)) {
        return property;
      }
    }
    return '';
  }

  setPostData(postData, propertyList = [], hasNullData = false) {
    for (let i = 0; i < propertyList.length; i++) {
      const property = propertyList[i];
      let value = this[property];
      if (SystemUtil.isEmpty(value)) {
        if (!hasNullData) {
          return;
        }
        value = '';
      }
      postData[property] = value;
    }
  }

  setDatetimeData(obj = {}, propertyList = []) {
    for (let i = 0; i < propertyList.length; i++) {
      const field = propertyList[i];
      let time = obj[field];
      if (SystemUtil.isEmpty(time)) {
        time = '';
      } else {
        time = moment(time).valueOf();
      }
      this[field] = time;
    }
  }

  getDatetimeValue(property, formatter = 'YYYY-MM-DD') {
    let time = this[property];
    if (SystemUtil.isEmpty(time)) {
      return '';
    }

    return moment(time).format(formatter);
  }
}
